package com.polaris.live.ui.user

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.View
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.lxj.xpopup.XPopup
import com.polaris.live.R.drawable
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.ActivityReleaseDynamicBinding
import com.polaris.live.interface_bag.S3UploadCallback
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.popup.SelectImagePopup
import com.polaris.live.translation.R
import com.polaris.live.utils.CropUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.viewmodel.home.DynamicViewModel
import com.yalantis.ucrop.UCrop

/**
 * 动态发布
 *
 * @author Created by 半仙 on 2024/9/4/004 14:52
 */
class ReleaseDynamicActivity : BaseVbActivity<DynamicViewModel, ActivityReleaseDynamicBinding>() {

    private var mPhotoUrl: String? = null

    override fun initView(savedInstanceState: Bundle?) {
        initListener()
        initObserver()
    }

    private fun initListener() {
        mBinding.etContent.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                val length = mBinding.etContent.text.length
                if (length < 10) {
                    mBinding.tvRelease.alpha = 0.3f
                } else {
                    mBinding.tvRelease.alpha = 1.0f
                }
                mBinding.tvNum.text = "${length}/500"
            }
        })
        mBinding.ivSelect.setOnSingleClickListener {
            XPopup.Builder(this)
                .moveUpToKeyboard(false)
                .isDestroyOnDismiss(true)
                .asCustom(SelectImagePopup(this, onSelectIt = { type ->
                    when (type) {
                        SelectImagePopup.CAMERA -> {
                            CropUtils.startCamera(this, { result ->
                                CropUtils.startCrop(this, result, 5f, 5f)
                            }, {
                            })
                        }

                        else -> {
                            CropUtils.startAlbum(this, {
                                showPhoto(it)
                            }, {}, 5f, 5f)
                        }
                    }
                }))
                .show()
        }
        //发布
        mBinding.tvRelease.setOnSingleClickListener {
            val text = mBinding.etContent.text
            if (text.length < 10) {
                ToastGravity.showGravity(StringUtils.getString(R.string.release_dynamic_rule))
                return@setOnSingleClickListener
            }
            upLoadPhoto()
        }
        //删除图片
        mBinding.ivDelete.setOnSingleClickListener {
            mBinding.ivDelete.visibility = View.GONE
            Glide.with(this).load(drawable.dynamic_add_image_back).into(mBinding.ivSelect)
            mPhotoUrl = null
        }
    }

    private fun initObserver() {
        mViewModel.sendDynamicLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(StringUtils.getString(R.string.published_successfully))
                finish()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun showPhoto(photoUrl: String) {
        Glide.with(this).load(photoUrl)
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .transform(RoundedCorners(8.autoDp))
            .into(mBinding.ivSelect)
        mPhotoUrl = photoUrl
        mBinding.ivDelete.visibility = View.VISIBLE
    }

    private fun upLoadPhoto() {
        showLoading(waitTime = 0L)
        val photoUrl = mPhotoUrl
        val content = mBinding.etContent.text.toString()
        if (photoUrl != null) {
            ImageUtils.s3Upload(
                photoUrl, AppConst.UpLoad.COMMUNITY, 1024,
                callback = object : S3UploadCallback {
                    override fun onSuccess(
                        url: String,
                        size: Pair<Int, Int>?,
                    ) {
                        mViewModel.releaseDynamic(content, url)
                        dismissLoading()
                    }

                    override fun onFailure(t: Throwable) {
                        ToastGravity.showGravity(t.message)
                        dismissLoading()
                    }
                })
        } else {
            mViewModel.releaseDynamic(content)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            data?.let { result ->
                val file = UriUtils.uri2File(UCrop.getOutput(result))
                file?.let { uploadFile ->
                    showPhoto(uploadFile.absolutePath)
                }
            }
        } else if (resultCode == RESULT_CANCELED && requestCode == UCrop.REQUEST_CROP) {
            CropUtils.startCamera(this, { result ->
                CropUtils.startCrop(this, result, 5f, 5f)
            }, {
            })
        }
    }
}